﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;

namespace AlertSystem.Business
{
    public partial class SysLog
    {
        public static void InsertLog(Exception e)
        {
            //Insert dữ liệu vào db
            try
            {
                using (var context = new DBDataContext(AppSetting.ConnectionString))
                {
                    context.SysLogs.InsertOnSubmit(
                        new SysLog()
                        {
                            log_message = e.Message,
                            log_source = e.Source,
                            log_stack_trace = e.StackTrace,
                            log_time = DateTime.Now
                        }
                    );
                    context.SubmitChanges();
                }
            }
            //Nếu không được thì insert dữ liệu vào file
            catch (Exception ex)
            {
                try
                {
                    Console.WriteLine(ex.Message);
                    string errmesage = "//////////////////////////////////////////\n" +
                                       "////////////////" + DateTime.Now + "/////////\n" +
                                       "log_mesage:      " + ex.Message + "\n" +
                                       "log_source:      " + ex.Source + "\n" +
                                       "log_stack_trace: " + ex.StackTrace + "\n";
                    using (StreamWriter writer = new StreamWriter(Path.Combine(HttpContext.Current.Server.MapPath(Path.Combine("~/App_Data", LogFileNam())), LogFileNam()), true))
                    {
                        writer.WriteLine(errmesage);
                    }
                }
                catch { }
            }
        }

        public static List<SysLog> Paging(int currentPage, int pageSize, ref int totalPage)
        {
            using (var context = new DBDataContext(AppSetting.ConnectionString))
            {
                var ret = context.SysLogs.Where(p => p.log_time >= DateTime.Now.Date.AddMonths(-3)).OrderByDescending(p => p.log_id);
                totalPage = ret.Count();
                return ret.ToList();
            }
        }

        static string LogFileNam()
        {
            return string.Format("smsrouter_log_{0}{1}{2}.txt", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
        }
    }
}
